package com.traffic.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.traffic.annotation.Power;
import com.traffic.constant.Const;
import com.traffic.constant.Status;
import com.traffic.entity.About;
import com.traffic.entity.Contact;
import com.traffic.exception.BaseException;
import com.traffic.mapper.ContactMapper;
import com.traffic.service.ContactService;
import com.traffic.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by IntelliJ IDEA.
 * User: KingRainGrey
 * Date: 2020/9/13
 */
@Service
public class ContactServiceImpl extends ServiceImpl<ContactMapper, Contact> implements ContactService {
    @Autowired
    private ContactMapper contactMapper;
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    @Transactional
    @Power(authority = Const.AUTH_TEXT)
    public Contact add(Contact contact) {
        if (jwtUtil.confirm(jwtUtil.getAccount(Const.TAG_ADMIN))) {
            QueryWrapper<Contact> wrapper = new QueryWrapper<>();
            wrapper.eq("status", Const.CONFIG_START);
            Contact old = contactMapper.selectOne(wrapper);
            if (ObjectUtil.isNotNull(old)) {
                old.setStatus(Const.CONFIG_CLOSE);
                contactMapper.updateById(old);
            }
            contact.setStatus(Const.CONFIG_START);
            contactMapper.insert(contact);
            return contact;
        }
        throw new BaseException(Status.COMMON_ERROR);
    }

    @Override
    public Contact get() {
        QueryWrapper<Contact> wrapper = new QueryWrapper<>();
        wrapper.eq("status", Const.CONFIG_START);
        Contact contact = contactMapper.selectOne(wrapper);
        return contact;
    }
}
